package org.opensource.webflux.socket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketMessage;
import org.springframework.web.reactive.socket.WebSocketSession;
import reactor.core.publisher.Mono;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class WebsocketHandler implements WebSocketHandler {

    private static Map<String, WebSocketSession> clients = new ConcurrentHashMap<>();

    @Override
    public Mono<Void> handle(final WebSocketSession session) {
        log.info("clientId = {}", session.getId());
        log.info("{}", clients);
        return session.send(
                session.receive()
                        .map(msg -> session.textMessage(
                                "服务端返回：小明， -> " + msg.getPayloadAsText()))
        );
    }

}
